/* layui 模块化 (其他要运行的js都写里面) */
var ws = null;
var url = null;
var transports = [];
var gys;
var jzgs;
var keyValue = $("#key").val();
layui.use(['layer','form','element'], function() {
  var layer = layui.layer; //弹层
  var form = layui.form; //form表单
  var element = layui.element;

  var $chatList = $('.chat-list'); //用户名列表容器
  var $chatBox = $('.chat-box'); ////聊天窗口容器

  function openChat(){
    layer.open({
      type: 1,
      title: '&#8203;',
      shade: 0,
      anim: 2,
      area: ['800px','520px'],
      maxmin: true,
      //closeBtn: false,
      content: $('#ltck'),
      full: function(index, layero){
        console.log('最大化');
        var clientHeight = $(document).height();
        var height = clientHeight - 50 - 182;
        $('.chat-main').height(height);
        $('.chat-list').height(clientHeight);
      },
      restore: function(index, layero){
        console.log('还原');
        $('.chat-main').height('292');
        $('.chat-list').height('520');
      }
    });
  }

  $('.openLtck').click(function(){
	//建立链接
	  if (typeof ws == undefined || ws == null){
		  connect();
	  }
    var id = $(this).attr('data-ltck');
    var name = $(this).attr('data-ltckName');

    gys = $("#gys").val();
    jzgs = $("#jzgs").val();
    
    
    openChat(); //打开聊天窗口弹窗
    addLtck(id,name); //添加一个用户聊天窗口
    
    //判断是否已经有聊天记录了, 空的话, 模拟加载一次聊天记录
    var $ltckLi = $('.chat-box .ltck-ct[data-ltck = '+ id +'] ul li');
    if($ltckLi.length == 0){
/*      addChatMain(id, getNowTime(), '您好'); //给 id=id 的聊天窗口添加一条"我"的信息
      addChatMain(id, getNowTime(), '您好', name); //给 id=id 的聊天窗口添加一条"d供应商"的信息
      addChatMain(id, getNowTime(), '<img src="${ctx}/res/images/choose.png" alt="">');*/
    }

  });




  /* 点击列表名字——切换聊天窗口 */
  $chatList.on('click', 'li', function(){

    var id = $(this).attr('data-ltck');
    $(this).siblings().removeClass('chat-this');
    $(this).addClass('chat-this');

    $('.chat-box .ltck-ct').removeClass('layui-show');
    $('.chat-box .ltck-ct[data-ltck = '+ id +']').addClass('layui-show');

    return false;
  });


  /* 点击x——关闭聊天窗口 */
  $chatList.on('click','li>i',function(event) {
    event.stopPropagation();

    var listLi = $(this).parent();
    var id = listLi.attr('data-ltck');

    closeChat(id, listLi);
    //disconnect();
  });

  /* 点击关闭按钮——关闭聊天窗口 */
  $chatBox.on('click','.send-close',function(event) {
    event.stopPropagation();

    var id = $(this).attr('data-ltck');
    var listLi = $('.chat-list li[data-ltck = '+ id +']');

    closeChat(id, listLi);
   // disconnect();
  });

  /* 回车键——发送消息 */
  $chatBox.on('click','textarea',function(event){
    var $this = $(this);
    var id = $(this).attr('data-ltck');
    $this[0].onkeydown = function(e){
      if(e.ctrlKey && e.which == 13 || e.which == 10){
        $this[0].value += "\n";
      }else if(e.keyCode == 13){
        // 避免回车键换行
        e.preventDefault();

        // 下面写你的发送消息的代码
        var text = $this.val();
        if(text.length != 0){
          sentChat($this);
        }
      }
    };

  });

  /* 点击发送按钮——发送信息 */
  $chatBox.on('click', '.send-btn', function(event) {
    event.stopPropagation();

    var id = $(this).attr('data-ltck');
    var $textarea = $('textarea[data-ltck = '+ id +']');
    var text = $textarea.val();

    if(text.length != 0){
    	sentChat($textarea);
    }
    
    
  });



  /* 关闭窗口 */
  function closeChat(id, listLi) {
    var listLiThis = listLi.hasClass('chat-this');
    var listLiNext = listLi.next();
    var listLiPrev = listLi.prev();



    listLi.remove();
    $('.chat-box .ltck-ct[data-ltck = '+ id +']').remove();

    if(listLiThis){

      if(listLiNext.length != 0){
        var nextId = listLiNext.attr('data-ltck');

        listLiNext.addClass('chat-this');
        var nextDiv = $('.chat-box .ltck-ct[data-ltck = '+ nextId +']');
        nextDiv.addClass('layui-show');
      }else if(listLiPrev.length != 0) {
        var prevId = listLiPrev.attr('data-ltck');
        listLiPrev.addClass('chat-this');
        var prevDiv = $('.chat-box .ltck-ct[data-ltck = '+ prevId +']');
        prevDiv.addClass('layui-show');
      }else {
        layer.close(layer.index);
      }

    }
  }


  /* 添加一个新的聊天窗口 */
  function addLtck (id, title){
    $('.chat-list li').removeClass('chat-this');
    $('.chat-box .ltck-ct').removeClass('layui-show');

    var $ltck = $('.chat-box .ltck-ct[data-ltck = '+ id +']');
    var $li = $('.chat-list li[data-ltck = '+ id +']');


    if($ltck.length == 0){
      var listLi = '<li class="chatlist-friend chat-this" data-ltck='+ id 
      +'> <span>'+ title +'</span> <i class="layui-icon">ဇ</i> </li>';
      var ltckCt = '<div class="ltck-ct layui-show" data-ltck='+ id 
      +'> <div class="chat-title"> <span>'+ title 
      +'</span> </div> <div class="chat-main"> <ul> </ul> </div> <div class="chat-footer"> <div class="layui-unselect chat-tool"> <span class="layui-icon tool-face" title="选择表情"></span> <span class="layui-icon tool-image" title="上传图片"><input type="file" name="file"></span> <span class="layui-icon tool-image" title="发送文件"><input type="file" name="file"></span> </div> <div class="chat-textarea"><textarea data-ltck='
      + id +'></textarea></div> <div class="chat-bottom"> <div class="chat-send"><span class="send-btn" data-ltck='+ id +'>发送</span> </div> </div> </div> </div>';

      $chatList.append(listLi);
      $chatBox.append(ltckCt);
    }else {
      $ltck.addClass('layui-show');
      $li.addClass('chat-this');
    }


  }


  /* 添加一条聊天信息 */
  function addChatMain (id, time, text, title){
    if(id != keyValue) {
      var chat = '<li> <div class="chat-user">  <cite>'+ jzgs +'<i>'+ time +'</i></cite> </div> <div class="chat-text">'+ text +'</div> </li>'
      var $chatMain = $('.ltck-ct[data-ltck = '+ id +'] .chat-main');
    }else {
      var chat = '<li class="chat-mine"> <div class="chat-user"> <cite><i>'+ time +'</i>'+gys+'</cite> </div> <div class="chat-text">'+ text +'</div> </li>'
      var $chatMain = $('.ltck-ct[data-ltck = '+ title +'] .chat-main');
    }
    
    var $chatMainUl = $chatMain.find('ul');
    var chatHeight = $chatMain.prop("scrollHeight");

    $chatMainUl.append(chat);
    $chatMain.animate({scrollTop:chatHeight}, 400);
    $("#key").val("");
  }


  /* 获取当前时间 */
  function getNowTime() {
    function p(s) {
      return s < 10 ? '0' + s: s;
    }

    var myDate = new Date();
    //获取当前年
    var year=myDate.getFullYear();
    //获取当前月
    var month=myDate.getMonth()+1;
    //获取当前日
    var date=myDate.getDate();
    var h=myDate.getHours();       //获取当前小时数(0-23)
    var m=myDate.getMinutes();     //获取当前分钟数(0-59)
    var s=myDate.getSeconds();

    var now=year+'-'+p(month)+"-"+p(date)+" "+p(h)+':'+p(m)+":"+p(s);

    return now;
  }


  /* 发送消息 */
  function sentChat($this) {
    var id = $this.attr('data-ltck');
    var text = $this.val();
    var time = getNowTime();
    sendMessage(id, time, text);
    $this.val('');
  }

  window.onbeforeunload = function(event) {
	    ws.onclose =function(){};
	    ws.close();
	};

	if (window.location.protocol == 'http:') {
	    url = 'ws://' + "192.168.0.11:8080" + "/yzbChat/yzbWebsocket/"+keyValue;
	    }
	//链接握手
	function connect() {
	  if (!url) {
	    alert('选择一个url');
	    return;
	  }
	    //判断链接中是否有sockjs，如果有使用sockjs的方式拼链接，如果没有发送ws链接
	  if(url.indexOf('sockjs') != -1){
	   //new SockJS(url, _reserved, options);默认三个参数，中间的基本不用，最后一个是sockjs提供的传输功能，参数是数组（默认是全部开启）
	     ws =new SockJS(url);
	  }else{
	     ws= new WebSocket(url);
	  }


	   //打开链接
	  ws.onopen = function () {
	  };
	  //获取消息
	  ws.onmessage = function (event) {
	  //调用下面的现实信息的方法
	  var rMsg = JSON.parse(event.data);
	  debugger;
//	  if (rMsg.from != keyValue){
		  addChatMain(rMsg.from, getNowTime(), rMsg.msg,rMsg.to);
//	  }else{
//		  addChatMain(rMsg.from, getNowTime(), rMsg.msg,rMsg.to);
//	  }
	  
	  };
	  //关闭链接
	  ws.onclose = function (event) {
	     //调用下面的现实信息的方法
	  };
	}

	//发送消息
	function sendMessage(id,time ,text) {
		
	  if (ws != null) {
	  //获取到输入框中的消息
//	    var message = document.getElementById('message').value;
	    var userMsg = {};
	    userMsg['id']=keyValue;
	    userMsg['to']=id;
	    userMsg['msg']=text;
	    alert(ws.readyState);
	     //调用下面的现实信息的方法
	    if (ws.readyState === 1){
	    	ws.send(JSON.stringify(userMsg));
	    }
	  } else {
	    alert('消息没有链接地址，请重新连接');
	  }
	}

	//关闭链接的时候将ws链接清空
	function disconnect() {
	  if (ws != null) {
	    ws.close();
	    ws = null;
	  }
	}

});



